package com.sumainfor.common.utlis;

import java.util.*;

/**
 * 功能描述:
 * List<Map<String,Object>>去重
 * @Auther: zhlu
 * @Date: 2019/3/12 15:42
 * @Description:
 */
public class ListMapRepeat {

    /**
     * 根据map中的某个key 去除List中重复的map
     * @author  zhlu
     * @param list
     * @param mapKey
     * @return
     */
    public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>>list, String mapKey){
        if (list.size()<=0) return null;

        //把list中的数据转换成msp,去掉同一id值多余数据，保留查找到第一个id值对应的数据
        List<Map<String, Object>>result=new ArrayList<Map<String,Object>>();
        Map<String, Map> msp = new HashMap<>();
        for(int i = list.size()-1 ; i>=0; i--){
            Map map = list.get(i);
            String id = (String)map.get(mapKey);
            map.remove(mapKey);
            msp.put(id, map);
        }
        //把msp再转换成list,就会得到根据某一字段去掉重复的数据的List<Map>
        Set<String> mspKey = msp.keySet();
        for(String key: mspKey){
            Map newMap = msp.get(key);
            newMap.put(mapKey, key);
            result.add(newMap);
        }

        return result;
    }


    public static void main(String[] args) {
        Map<String, Map> msp = new HashMap<String, Map>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("Province", "上海市");
        map1.put("city", "市辖区");
        map1.put("District", "浦东新区");
        map1.put("Street", "唐镇");
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("Province", "上海市");
        map2.put("city", "市辖区");
        map2.put("District", "浦东新区");
        map2.put("Street", "唐镇");
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("Province", "上海市");
        map3.put("city", "市辖区");
        map3.put("District", "杨浦区");
        map3.put("Street", "五角场街道");
        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("Province", "上海市");
        map4.put("city", "市辖区");
        map4.put("District", "虹口区");
        map4.put("Street", "江湾镇街道");
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        System.out.println("初始数据：" + list.toString());
        System.out.println("去重之后：" + removeRepeatMapByKey(list,"District"));
    }
}
